// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
import moment from 'moment'
// 引入antd的组件
import {
  Form,
  Row,
  Col,
  Input,
  DatePicker,
  Upload,
  message,
  Table ,
  Select,
  Button,
  Modal,
  Popconfirm,
  Tooltip,
  Icon ,
  Checkbox
} from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// import {  isEmpty, isArray, cloneDeep, chunk,  set } from 'lodash'
// import Cookie from 'js-cookie'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// import { reg } from 'utils/util'
// 当前组件样式
import styles from './commissionsRulesEditStyle.less'

import ListPage from 'widget/PageTmpl/ListPage'
import Uploader from 'widget/Upload'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import { Grid, QueryCondition } from 'widget/Grid/index'
import classnames from 'classnames/bind'
let cx = classnames.bind(styles);

const FormItem = Form.Item
const { TextArea } = Input;
// const { RangePicker } = DatePicker;

const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 15 },
}
const formItemLayout01 = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
}


/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const commissionsDistRulesDetailView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { getFieldDecorator, validateFieldsAndScroll,setFieldsValue,getFieldsValue} = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let {createFaymentMethodFlag,projectList,userList,searchData,productListObj,productPageConfig,submitType,distCoId,formatsKey,tableObj,actionType, id,keys,distributionNameList, projectModalObj,tableData, pageConfig, loading, selectedRowKeys, formatsModalObj,detail,accountingModalObj,selectedRows,userNameModalObj} = modelObj
  
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      dispatch({
        type: `${namespace}/selectedKeysChange`,
        payload: {selectedRowKeys,selectedRows}
      })
    },
    type: 'radio'
  };

  const columns = [
    {
      title: "序号",
      dataIndex: '',
      key: '',
      width: 80,
      render: (a, item, index, d, e, f) => {
        return index+1
      },
    },
    {
      title: '区域',
      dataIndex: 'provinceName',
      key: 'provinceName',
    },
    {
      title: '城市',
      dataIndex: 'cityName',
      key: 'cityName',
    },
    {
      title: '项目',
      dataIndex: 'pname',
      key: 'pname',
    },
    {
        title: '项目编码',
        dataIndex: 'projectCode',
        key: 'projectCode',
      },
  ]

  // 表格配置------------开始
  const columns1 = [

    {
      title: '业态名称', dataIndex: 'productname', key: 'productname', width: 200,
      render: function (value, item, index) {
        return <div>
          <Input value = {item.productname} disabled={actionType == 'check'} readOnly={true}
                placeholder={'请输入业态名称'}
                onChange={(e) => { tableChange(e.target.value, 'productname',index) }}
                onClick={() => { updateFormatsName(value,item,index) }}
              />
        </div>
      }
    },
    {
    title: '返佣方式', dataIndex: 'fytype', key: 'fytype', width: 120,
    render: function (value, item, index) {
    
        return <div>
            <Select disabled={actionType == 'check'} placeholder="请选择返佣方式" value={item.fytype}   onChange={(e)=>{tableChangeCommType(e,'fytype',index)}}>
                <Select.Option value="0">金额</Select.Option>
                <Select.Option value="1">比例</Select.Option>
            </Select>
    </div>
    }
    },
    {
      title: '比例（如0.01;<=0.05）', dataIndex: 'proportion', key: 'proportion', width: 200,
      render: function (value, item, index) {
        return <div>
          <Input value = {item.proportion} disabled={actionType == 'check'||tableData.dataSource[index].fytype=='0'}
              onChange={(e) => { tableChange(e.target.value.replace(/[^\-?\d.]/g,''), 'proportion',index) }}
            />
        </div>
      }
    },
    {
      title: '金额', dataIndex: 'amount', key: 'amount', width: 160,
      render: function (value, item, index) {
        return <div>
        <Input value = {item.amount} disabled={actionType == 'check'||tableData.dataSource[index].fytype=='1'}
            onChange={(e) => { tableChange(e.target.value.replace(/[^\-?\d.]/g,''), 'amount',index) }}
          />
      </div>
      }
    },
    {
      title: '备注', dataIndex: 'remark', key: 'remark', width: 200,
      render: function (value, item, index) {
        return <div>
                <Input value = {item.remark} disabled={actionType == 'check'}
                    onChange={(e) => { tableChange(e.target.value, 'remark',index) }}
                  />
              </div>
      }
    },
  ]
 
  const gridProps = {
    nameSpace: namespace,
    selectedKeysChange: 'selectedKeysChange',
    data: {
      columns: columns1
      ,
      pageConfig, tableData, selectedRowKeys,
    },
    pageChange: (pageNo, pageSize) => {
      tableData = { ...tableData, pageNo, pageSize }
      pageConfig = { ...pageConfig, pageNo, pageSize }
      changeState({ tableData, pageConfig });
    },
    scroll: { x: 800 },
    loading
  }
   // 用户
   const columns3 = [
    {
      title: '序号', dataIndex: 'ruleNo', key: 'ruleNo',width:100,
      render: function (value, item, index) {
        return index+1
      }
    }, 
    {
      title: '用户', dataIndex: 'authenticationId', key: 'authenticationId',
      render: function (value, item, index) {
        return item.authenticationId
      }
    },
    {
        title: '用户名称', dataIndex: 'name', key: 'name',
        render: function (value, item, index) {
          return item.name
        }
      }
  ]

  // 业态
  const columns2 = [
    {
      title: '序号', dataIndex: 'ruleNo', key: 'ruleNo',width:100,
      render: function (value, item, index) {
        return index+1
      }
    }, 
    {
      title: '业态名称', dataIndex: 'combinationName', key: 'combinationName',
      render: function (value, item, index) {
        return item.combinationName
      }
    }
  ]
  let selectedRowKeysTemp =  tableData.dataSource.length?tableData.dataSource.filter(item =>item.key == formatsKey)[0]:{}
  let productSelectedKeys = selectedRowKeysTemp&&selectedRowKeysTemp.productSelectedKeys?selectedRowKeysTemp.productSelectedKeys:[]
  let gridProps1 = {
    nameSpace: namespace,
    selectedKeysChange: 'selectedKeysChange1',
    data: {
      columns: columns2,
      pageConfig:productPageConfig, tableData:productListObj,
      selectedRowKeys: productSelectedKeys,
    },
    pageChange: (pageNo, pageSize) => {
      productListObj.pageNo = pageNo
      productListObj.pageSize = pageSize
      productPageConfig.pageNo = pageNo
      productPageConfig.pageSize = pageSize
      tableData = productListObj
      pageConfig = productPageConfig
      changeState({ productListObj, productPageConfig});
    },
    scroll: { x: 800 },
    loading
  }

  //修改状态
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { ...payload }
    })
  }
  //详情页跳转
  function routerGo() {
    hashHistory.push({
      pathname: '/home/commissions/commissionsRules',
      query: {}
    })
  }
  //关闭
  function onCancel(){
    routerGo()
  }
  // 保存
  function save(type) {
    submitType = type
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/updateStore`,
          payload: {submitType}
        })
        dispatch({
          type: `${namespace}/create`,
          payload: {}
        })
      }
    })
  }
    //项目名称弹窗事件 
function updateProjectName(){
    projectModalObj.visible = !projectModalObj.visible
    changeState({ projectModalObj})
    dispatch({
        type: `${namespace}/selectProject`,
        payload: {}
    })
    }
    function confirmProject(){
    accountingModalObj.isTransferProperty = selectedRows[0]&&selectedRows[0].isTransferProperty?selectedRows[0].isTransferProperty:'0'
    accountingModalObj.projectid = selectedRows[0]&&selectedRows[0].projectId?selectedRows[0].projectId:''
    detail.projectname = selectedRows[0]&&selectedRows[0].pname?selectedRows[0].pname:''
    detail.pkProject = selectedRows[0]&&selectedRows[0].projectId?selectedRows[0].projectId:''
    detail.projectid = selectedRows[0]&&selectedRows[0].projectId?selectedRows[0].projectId:''
    detail.zyx3 = selectedRows[0]&&selectedRows[0].zyx1?selectedRows[0].zyx1:''
    dispatch({
        type: `${namespace}/updateStore`,
        payload: {detail,createFaymentMethodFlag,accountingModalObj}
    })
    dispatch({
        type: `${namespace}/selectSubject`,
        payload: {}
    })
    form.resetFields()
    updateProjectName()
    }
 //项目查询
 function searchFun(){
    dispatch({
        type: `${namespace}/selectProject`,
        payload: {}
    })
  }
  function clearFun(){
    accountingModalObj.projectName = ''
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {accountingModalObj}
    })
  }
  // 搜索
  function inputSearch (value, name) {
    let obj = {[name]: value}
    accountingModalObj = Object.assign(accountingModalObj, obj)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {accountingModalObj}
    })
  }
     //用户名称弹窗事件 
function updateUserName(){
    userNameModalObj.visible = !userNameModalObj.visible
    changeState({ userNameModalObj})
    // dispatch({
    //     type: `${namespace}/listQuery`,
    //     payload: {}
    // })
    }
    function confirmProject1(){   
    detail.zyx1 = selectedRows[0]&&selectedRows[0].authenticationId?selectedRows[0].authenticationId:'';
    detail.zyx2 = selectedRows[0]&&selectedRows[0].name?selectedRows[0].name:''
    dispatch({
        type: `${namespace}/updateStore`,
        payload: {detail,createFaymentMethodFlag,accountingModalObj}
    })
    dispatch({
        type: `${namespace}/listQuery`,
        payload: {}
    })
    form.resetFields()
    updateUserName()
    }
 //用户查询
 function searchFun1(){
    // accountingModalObj.zyx1 = '46543654'
    console.log(accountingModalObj.zyx2);
    dispatch({
        type: `${namespace}/listQuery`,
        payload: {accountingModalObj}
    })
  }
  function clearFun1(){
    accountingModalObj.zyx2 = ''
    dispatch({
      type: `${namespace}/listQuery`,
      payload: {accountingModalObj}
    })
  }
  // 搜索
  function inputSearch1 (value, name) {
    let obj = {[name]: value}
    accountingModalObj = Object.assign(accountingModalObj, obj)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {accountingModalObj}
    })
  }
  //业态名称弹窗事件
  function updateFormatsName(value,item,index){
    formatsModalObj.visible = !formatsModalObj.visible
    if(item){
      formatsKey = item.key
    }
    changeState({ formatsModalObj,formatsKey})
  }
  function confirmFormats(){
    for(var item of tableData.dataSource){
      if(item.key == formatsKey){
        let list = item.productSelectedRows.length?item.productSelectedRows.map(itt =>{
          return {
            productname: itt.combinationName,
            id: itt.id
          }
        }):[]
        // for(var itp of list){
        //   for(var ipt of item.productList){
        //     if(itp.productId == ipt.productId){
        //       itp.falg = 1
        //     }
        //   }
        // }
        // list = list.filter(ppt =>ppt.falg !=1)
        // item.productList.push(...list)
        item.productList = list
        let name1 = item.productSelectedRows.length?item.productSelectedRows.map(itt =>{
          return itt.combinationName
        }).join(','):''
        item.productname = name1;
        item.productid = list.id;
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData}
    })
    updateFormatsName()
  }

  // 添加
  function updateModal() {
    
    tableObj.key = ++keys
    let obj = JSON.parse(JSON.stringify(tableObj))
    tableData.dataSource.push(obj);
    console.log(tableData.dataSource);
    changeState({ tableData,keys})
  }

  //批量删除选中项
  function deleteItems() {
    let arr = []
    tableData.dataSource.map((item, index) => {
      if (selectedRowKeys.indexOf(item.key) == -1) {
        arr.push(item)
      }
    })
    tableData.dataSource = arr
    tableData.total = tableData.dataSource.length
    changeState({ tableData })
  }
  //表单改变时
  function inputChange (value, name) {
    let obj = {[name]: value}
    detail = Object.assign(detail, obj)

    dispatch({
    type: `${namespace}/updateStore`,
    payload: {detail}
    })
    
  }

  //表格改变时
  function tableChange (value, name,id) {
      if(name=='proportion'){
          value = value<=0.05?value:0;
      }
    let obj = {[name]: value}
    tableData.dataSource.forEach((element,index) => {
        if(index == id){
            element = Object.assign(element, obj)
          }
    });
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData}
    })
  }
  function tableChangeCommType(value, name,id){
    let obj = {[name]: value};
    for(var item of tableData.dataSource){
    //   if(item.key == id){
        tableData.dataSource[id].amount = ''
        tableData.dataSource[id].proportion	 = ''
        tableData.dataSource[id] = Object.assign(tableData.dataSource[id], obj)
        if(value == '金额'){
            tableData.dataSource[id].fytype = '金额'
        }else if(value == '比例'){
            tableData.dataSource[id].fytype = '比例'
        }
        console.log(tableData.dataSource[id]);
    //   }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData}
    })
  }
  //赋值distCoId
  function tableChangeDistCoId (value, name,id) {
    let obj = {[name]: value}
    for(var item of distributionNameList){
        if(item.orgName == value){
          distCoId = item.orgId
        }
    }
    for(var item of tableData.dataSource){
      if(item.key == id){
        item = Object.assign(item, obj)
        item['distCoId'] = distCoId
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData}
    })
  }
  return (
    <div className={cx('public_listMain')}>
      <div className="functionButton">
        <Button disabled={actionType == 'check'} type='primary' onClick={() => { save() }}>保存</Button>
        <Popconfirm  disabled={actionType == 'check'} placement="top" title={"是否确认关闭，确认后关闭页面，不保存数据。"} onConfirm={() => onCancel()} okText="确定" cancelText="取消">
          <Button>关闭</Button>
        </Popconfirm>
      </div>
      <CollapsiblePanels title="佣金规则" hideUpDownBtn={true}>
        <Row>
            <Col className="col" span={8}>
            <FormItem {...formItemLayout}
              label="是否生效">
              {getFieldDecorator('iseffective', {
                initialValue: detail.iseffective,
                rules: [
                  { required: true, whitespace: true, message: '是否生效', },
                ],
              })(
              <Select disabled={actionType == 'check'} placeholder="是否生效" onChange={(e)=>{inputChange(e,'iseffective')}}>
                    <Select.Option value="Y">是</Select.Option>
                    <Select.Option value="N">否</Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>
        <Col className="col" span={8}>
            <FormItem {...formItemLayout}
              label="项目名称">
              {getFieldDecorator('projectname', {
                initialValue: detail.projectname,
                rules: [
                  { required: true, whitespace: true, message: '请输入项目名称', },
                ],
              })(<Input disabled={actionType == 'check'} readOnly={true}
                placeholder={'请输入项目名称'}
                onChange={(e) => { inputChange(e.target.value, 'projectname') }}
                onClick={() => { updateProjectName() }}
              />)}
            </FormItem>
          </Col>
          <Col className="col" span={8}>
            <FormItem {...formItemLayout}
              label="佣金提单人">
              {getFieldDecorator('zyx2', {
                initialValue: detail.zyx2,
                rules: [
                  { required: true, whitespace: true, message: '请输入提单人', },
                ],
              })(<Input disabled={actionType == 'check'} readOnly={true}
                placeholder={'请输入提单人'}
                onChange={(e) => { inputChange(e.target.value, 'zyx2') }}
                onClick={() => { updateUserName() }}
              />)}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col className="col" span={8}>
              <FormItem
                  {...formItemLayout}
                  label="生效日期"
                  >
                  {getFieldDecorator('startdate', {
                    rules:[{required:true,message:'请选择生效时间'},],
                    initialValue: detail.startdate ? moment(detail.startdate, 'YYYY-MM-DD') : null
                  })(
                    <DatePicker disabled={actionType == 'check'} format="YYYY-MM-DD" onChange={(e, val) => inputChange(val, 'startdate')}  />
                  )}
              </FormItem>
          </Col>
          <Col className="col" span={8}>
              <FormItem
                  {...formItemLayout}
                  label="失效日期"
                  >
                  {getFieldDecorator('enddate', {
                    rules:[{required:true,message:'请选择失效时间'},],
                    initialValue: detail.enddate ? moment(detail.enddate, 'YYYY-MM-DD') : null
                  })(
                    <DatePicker disabled={actionType == 'check'} format="YYYY-MM-DD" onChange={(e, val) => inputChange(val, 'enddate')}  />
                  )}
              </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={16}>
            <FormItem {...formItemLayout01}
              label="备注">
              {getFieldDecorator('remark', {
                initialValue: detail.remark,
                rules: [
                  { required: false, whitespace: true, message: '', },
                ],
              })(
              <TextArea disabled={actionType == 'check'} style={{width:500}} onChange={e=>{inputChange(e.target.value,'remark')}}></TextArea>
              )}
            </FormItem>
          </Col>
        </Row> 

      </CollapsiblePanels>

      <CollapsiblePanels title="佣金规则明细" hideUpDownBtn={true} >
        <div className="clearfix mgb1">
          <div className={cx('fr')}>
            <Button  disabled={actionType == 'check'||detail.noCommission} type='primary' onClick={() => { updateModal() }}>添加</Button>
           
            <Popconfirm placement="top" title={"确定删除选中项吗？"} onConfirm={() => deleteItems()} okText="确定" cancelText="取消">
              <Button type='primary'  disabled={actionType == 'check'||detail.noCommission} className='mgl1'>删除</Button>
            </Popconfirm>
          </div>
        </div>
        <div className={cx('mt1', 'table_projectList')} style={{display:detail.noCommission?'none': 'block'}}>
          <Form>
            <Grid {...gridProps}/>
          </Form>
        </div>
      </CollapsiblePanels>
        {/*选择项目弹窗*/}
        <Modal
        title={'所属项目'}
        width='1000px'
        visible={projectModalObj.visible}
        destroyOnClose={true}
        onCancel={() => { updateProjectName() }}
        onOk={() => { confirmProject() }}
      >
           <div style={{marginBottom:'12px'}}>
            <Row>
            <Col span={2} style={{lineHeight:'28px'}}>
            <label>项目名称</label>:
            </Col>
            <Col span={6} style={{marginRight:'10px'}}>
            <Input  value ={accountingModalObj.projectName} placeholder="请输入项目名称" onChange={(e) => { inputSearch(e.target.value, 'projectName') }}/>
            </Col>
            <Col span={8}></Col>
            <Col span={6}>
                <Button type='primary' onClick={() => {searchFun()}}>查询</Button>
                <Button style={{marginLeft: '12px'}} onClick={() => {clearFun()}}>重置</Button>
            </Col>
            </Row>
        </div>     
        <div>
            <Table rowKey={(item, index) => {
                    return item.projectId
            }}  rowSelection={rowSelection} columns={columns} dataSource={projectList} type={'radio'}/>
        </div>
      </Modal>
       {/*选择项目弹窗*/}
       <Modal
        title={'用户'}
        width='1000px'
        visible={userNameModalObj.visible}
        destroyOnClose={true}
        onCancel={() => { updateUserName() }}
        onOk={() => { confirmProject1() }}
      >
           <div style={{marginBottom:'12px'}}>
            <Row>
            <Col span={2} style={{lineHeight:'28px'}}>
            <label>用户名称</label>:
            </Col>
            <Col span={6} style={{marginRight:'10px'}}>
            <Input  value ={accountingModalObj.zyx2} placeholder="请输入用户名称" onChange={(e) => { inputSearch1(e.target.value, 'zyx2') }}/>
            </Col>
            <Col span={8}></Col>
            <Col span={6}>
                <Button type='primary' onClick={() => {searchFun1()}}>查询</Button>
                <Button style={{marginLeft: '12px'}} onClick={() => {clearFun1()}}>重置</Button>
            </Col>
            </Row>
        </div>     
        <div>
            <Table rowKey={(item, index) => {
                    return item.accountId
            }}  rowSelection={rowSelection} columns={columns3} dataSource={userList} type={'radio'}/>
        </div>
      </Modal>
        {/*新销售系统业态档案弹窗*/}
        <Modal
          title={'新销售系统业态档案'}
          width='800px'
          destroyOnClose={true}
          visible={formatsModalObj.visible}
          onCancel={() => { updateFormatsName() }}
          onOk={() => { confirmFormats() }}
        >
          <div>
              {/* <ListPage pageProps={pageProps1}/> */}   
              <Grid {...gridProps1} />
          </div>
        </Modal>

    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(commissionsDistRulesDetailView))
